package logic

import (
	"context"

	model "paper-pro/app/assistant/model/assistant"
	"paper-pro/app/assistant/rpc/internal/svc"
	"paper-pro/app/assistant/rpc/pb"
	"paper-pro/pkg/xerr"

	"github.com/pkg/errors"
	"github.com/zeromicro/go-zero/core/logx"
)

type GetAssistantMetasLogic struct {
	ctx    context.Context
	svcCtx *svc.ServiceContext
	logx.Logger
}

func NewGetAssistantMetasLogic(ctx context.Context, svcCtx *svc.ServiceContext) *GetAssistantMetasLogic {
	return &GetAssistantMetasLogic{
		ctx:    ctx,
		svcCtx: svcCtx,
		Logger: logx.WithContext(ctx),
	}
}

func (l *GetAssistantMetasLogic) GetAssistantMetas(in *pb.GetAssistantMetasReq) (*pb.GetAssistantMetasResp, error) {
	assistantMetas, err := l.svcCtx.AssistantModel.FindMetas(l.ctx, in.UserId)
	if err != nil {
		if err == model.ErrNotFound {
			return nil, xerr.NewErrMsg("未查询到助理数据")
		}
		return nil, errors.Wrapf(xerr.NewErrCode(xerr.DB_ERROR),
			"查询助理列表数据失败，用户ID: %d, err: %v", in.UserId, err)
	}

	metaCount := len(assistantMetas)
	assistantMetaResp := make([]*pb.AssistantMeta, metaCount)
	for i := 0; i < metaCount; i++ {
		assistantMetaResp[i] = &pb.AssistantMeta{}
		assistantMetaResp[i].Id = assistantMetas[i].ID.Hex()
		assistantMetaResp[i].Name = assistantMetas[i].Name
		assistantMetaResp[i].LastUseAt = assistantMetas[i].LastUseAt.Unix()
	}

	return &pb.GetAssistantMetasResp{
		AssistantMetas: assistantMetaResp,
	}, nil
}
